package com.zixuan.yuojbackendjudgeservice.judge;

import cn.hutool.json.JSONUtil;
import com.zixuan.yuojbackendcommon.common.ErrorCode;
import com.zixuan.yuojbackendcommon.exception.BusinessException;
import com.zixuan.yuojbackendjudgeservice.judge.codesandbox.CodeSandBox;
import com.zixuan.yuojbackendjudgeservice.judge.codesandbox.CodeSandBoxFactory;
import com.zixuan.yuojbackendjudgeservice.judge.codesandbox.CodeSandBoxProxy;
import com.zixuan.yuojbackendjudgeservice.judge.codesandbox.model.ExecuteCodeRequest;
import com.zixuan.yuojbackendjudgeservice.judge.codesandbox.model.ExecuteCodeResponse;
import com.zixuan.yuojbackendjudgeservice.judge.strategy.JudgeContext;
import com.zixuan.yuojbackendjudgeservice.judge.strategy.JudgeManage;
import com.zixuan.yuojbackendmodel.model.codesandbox.JudgeInfo;
import com.zixuan.yuojbackendmodel.model.dto.question.JudgeCase;
import com.zixuan.yuojbackendmodel.model.entity.Question;
import com.zixuan.yuojbackendmodel.model.entity.QuestionSubmit;
import com.zixuan.yuojbackendmodel.model.enums.JudgeInfoMessageEnum;
import com.zixuan.yuojbackendmodel.model.enums.QuestionSubmitStatusEnum;
import com.zixuan.yuojbackendserviceclient.service.QuestionFeignClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;
/**
 * @author Mr.Mei
 * @date 2023/11/14
 */
@Service
@Slf4j
public class JudgeServiceImpl implements JudgeService {

    @Value("${sandbox.type:example}")
    private String type;
    @Resource
    private QuestionFeignClient questionFeign;

    @Override
    public QuestionSubmit doJudge(long questionSubmitId) {

        QuestionSubmit questionSubmit = questionFeign.getQuestionSubmitById(questionSubmitId);
        // 提交记录不存在
        if (questionSubmit == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "提交记录不存在");
        }
        Long questionId = questionSubmit.getQuestionId();
        Question question = questionFeign.getQuestionById(questionId);
        // 题目不存在
        if (question == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "题目不存在");
        }
        // 正在判题，不允许再次申请
        if (!questionSubmit.getStatus().equals(QuestionSubmitStatusEnum.WAITING.getValue())) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "题目正在判题");
        }
        QuestionSubmit submit = new QuestionSubmit();
        submit.setId(questionSubmitId);
        submit.setStatus(QuestionSubmitStatusEnum.RUNNING.getValue());
        boolean update = questionFeign.updateQuestionSubmitById(submit);
        // 更新判题状态
        if (!update) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "题目状态更新错误");
        }

        String language = questionSubmit.getLanguage();
        String code = questionSubmit.getCode();

        String judgeCase = question.getJudgeCase();
        List<JudgeCase> judgeCaseList = JSONUtil.toList(judgeCase, JudgeCase.class);
        List<String> inputList = judgeCaseList.stream().map(JudgeCase::getInput).collect(Collectors.toList());

        // 调用沙箱
        CodeSandBox codeSandBox = CodeSandBoxFactory.newInstance(type);
        codeSandBox = new CodeSandBoxProxy(codeSandBox);
        ExecuteCodeRequest executeCodeRequest = ExecuteCodeRequest.
                builder()
                .code(code)
                .language(language)
                .inputList(inputList)
                .build();
        ExecuteCodeResponse executeCodeResponse = codeSandBox.executeSandBox(executeCodeRequest);
        System.out.println("executeCodeResponse=====>{}:::"+executeCodeResponse);
        List<String> outputList = executeCodeResponse.getOutputList();

        // 根据执行结果，设置沙箱状态
        JudgeContext judgeContext = new JudgeContext();
        judgeContext.setJudgeInfo(executeCodeResponse.getJudgeInfo());
        judgeContext.setOutputList(outputList);
        judgeContext.setInputList(inputList);
        judgeContext.setQuestion(question);
        judgeContext.setJudgeCaseList(judgeCaseList);
        judgeContext.setQuestionSubmit(questionSubmit);
        JudgeManage judgeManage = new JudgeManage();
        JudgeInfo judgeInfo = judgeManage.doJudge(judgeContext);//对判题机返回的结果进行比对 ACCEPTED
        if(judgeInfo==null){
            judgeInfo.setMessage(JudgeInfoMessageEnum.SYSTEM_ERROR.getText());
            judgeInfo.setMemory(0L);
            judgeInfo.setTime(0L);
        }
        submit = new QuestionSubmit();
        submit.setId(questionSubmitId);
        submit.setStatus(QuestionSubmitStatusEnum.SUCCEED.getValue());
        submit.setJudgeInfo(JSONUtil.toJsonStr(judgeInfo));//null
        log.info("judgeInfo=====>{}",submit.getJudgeInfo());
        System.out.println("judgeInfo=====>{}:::"+submit.getJudgeInfo());
        update = questionFeign.updateQuestionSubmitById(submit);
        // 更新判题状态
        if (!update) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "题目状态更新错误");
        }

        QuestionSubmit questionSubmitResponse = questionFeign.getQuestionSubmitById(submit.getId());
        //更新题目通过率
         questionId = questionSubmitResponse.getQuestionId();
         question = questionFeign.getQuestionById(questionId);
         question.setSubmitNum(question.getSubmitNum()+1);
        String message = judgeInfo.getMessage();
        if(message.equals(JudgeInfoMessageEnum.ACCEPTED.getText())){
             question.setAcceptedNum(question.getAcceptedNum()+1);
         }
        update = questionFeign.updateQuestionById(question);
        if (!update) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "题目通过率更新错误");
        }
        return questionSubmitResponse;
    }
}
